package com.example.pei.papa.fragments;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.example.pei.papa.activity.MainActivity;

import java.io.File;

//import java.text.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


import com.example.pei.papa.R;
import com.example.pei.papa.adapter.NineGridTestAdapter;
import com.example.pei.papa.dialog.dynamicSelectedDialog;
import com.example.pei.papa.tables.AlumniCircle;
import com.example.pei.papa.tables.UserInfo;
import com.example.pei.papa.tables.praises;
import com.example.pei.papa.tables.shielding;
import com.mingle.widget.ShapeLoadingDialog;
import com.tencent.bugly.crashreport.CrashReport;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DeleteBatchListener;
import cn.bmob.v3.listener.DownloadFileListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static android.app.Activity.RESULT_OK;
import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;
import static cn.bmob.v3.Bmob.getApplicationContext;
import static com.example.pei.papa.utils.SnackbarUtil.ShowSnackbar;


/**
 *
 */
public class tabbarFragments extends Fragment {

    public final static int ADDDYNAMIC=1008;

    private FrameLayout fragmentContainer;
    private dynamicSelectedDialog mDynamicSelectedDialog;


    public static tabbarFragments newInstance(int index) {
        tabbarFragments fragment = new tabbarFragments();
        Bundle b = new Bundle();
        b.putInt("index", index);
        fragment.setArguments(b);
        return fragment;
    }

    View view1;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {



        if (getArguments().getInt("index",0) == 0) {
            if(view1==null) {
                view1 = inflater.inflate(R.layout.homemune_fragment, container, false);
                initHomeMenu(view1);
                initHomeDate();
            }
            return view1;
        } else if (getArguments().getInt("index",0) == 1){
            View view = inflater.inflate(R.layout.homemune_fragment, container, false);
            initHomeMenu(view);
            return view;
        } else if (getArguments().getInt("index",0) == 2){
            View view = inflater.inflate(R.layout.homemune_fragment, container, false);
            initHomeMenu(view);
            return view;
        } else if (getArguments().getInt("index",0) == 3){
            View view = inflater.inflate(R.layout.homemune_fragment, container, false);
            initHomeMenu(view);
            return view;
        } else{
            View view = inflater.inflate(R.layout.personalmenu_fragment, container, false);
            initPersonalMenu(view);
            return view;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        } else {
            switch (requestCode){
                case ADDDYNAMIC:
                    ShowSnackbar(getView()," 发表成功~","#FFAF70","#ffffff",16);
                    break;
            }
        }
    }
    /**
     * Init demo settings
     */
   // public static final int PULLNUM=15; //初始化时第一次先从服务器拉PULLNUM个动态下来
    private static final int STATE_REFRESH = 0;// 下拉刷新
    private static final int STATE_MORE = 1;// 加载更多

    // private LinearLayoutManager mLayoutManager;
    private NineGridTestAdapter mAdapter;

    private SwipeToLoadLayout swipeToLoadLayout;

 //   private List<AlumniCircle> mList = new ArrayList<>();


    private Date oldestDynamicDate;  //最老的动态时间




    private void initHomeMenu(View view) {
        final MainActivity t = (MainActivity) getActivity();
        if(t==null) return;


        RecyclerView mRecyclerView = (RecyclerView) view.findViewById(R.id.swipe_target);

        RelativeLayout title=(RelativeLayout)view.findViewById(R.id.homefragment_include);
        Button button_add = (Button) title.findViewById(R.id.btn_add);
        button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent("add_dynamic_Activity");
                String username=t.getCurrentUser().getUsername();
                String userphone=t.getCurrentUser().getMobilePhoneNumber();
                int usersex=t.getCurrentUser().getSex();
                intent.putExtra("username",username);
                intent.putExtra("userphone",userphone);
                intent.putExtra("usersex",usersex);
                startActivityForResult(intent,ADDDYNAMIC);
            }
        });

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);

        mRecyclerView.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        mAdapter = new NineGridTestAdapter(getContext(),new NineGridTestAdapter.itemListener(){
            @Override
            public void onThreePointClick(View v,final int position) {
                View vieww = getLayoutInflater().inflate(R.layout.save_photo_dialog, null);
                int permission=0;
                //如果是自己发送的或者是管理员 则可以删除
                if(mAdapter.getmList().get(position).getSenderID().equals(t.getCurrentUser().getUsername())&&t.getCurrentUser().getUserType()==1){
                    //是自己发送的，且不是管理员,普通用户
                    permission=1;
                } else if(mAdapter.getmList().get(position).getSenderID().equals(t.getCurrentUser().getUsername())&&t.getCurrentUser().getUserType()==0){
                    //是自己发送的，且是管理员
                    permission=2;
                }else if(!mAdapter.getmList().get(position).getSenderID().equals(t.getCurrentUser().getUsername())&&t.getCurrentUser().getUserType()==0){
                    //不是自己发送的，但是是管理员
                    permission=3;
                }else if(!mAdapter.getmList().get(position).getSenderID().equals(t.getCurrentUser().getUsername())&&t.getCurrentUser().getUserType()==1){
                    //不是自己发送的，且不是管理员
                    permission=0;
                }

                mDynamicSelectedDialog=new dynamicSelectedDialog(getContext(), R.style.transparentFrameWindowStyle,permission, new dynamicSelectedDialog.Listener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()){
                            case R.id.btn_copy:
                                //获取剪贴板管理器：
                                ClipboardManager cm = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                                // 创建普通字符型ClipData
                                ClipData mClipData = ClipData.newPlainText("Label", mAdapter.getmList().get(position).getContent());
                                // 将ClipData内容放到系统剪贴板里。
                                cm.setPrimaryClip(mClipData);
                                Toast.makeText(getActivity(),"已经复制好啦!",Toast.LENGTH_SHORT).show();
                                break;
                            case R.id.btn_shield:
                                shieldSkill(position);
                                break;
                            case R.id.btn_del:
                                //删除数据库里的内容
                                deleteSkill(position);
                                break;
                          }
                        mDynamicSelectedDialog.dismiss();
                    }
                });
                mDynamicSelectedDialog.setContentView(vieww, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
                Window window = mDynamicSelectedDialog.getWindow();
                // 设置显示动画
                //   window.setWindowAnimations(R.style.main_menu_animstyle);
                WindowManager.LayoutParams wl = window.getAttributes();
                wl.x = 0;
                // wl.y = (getWindowManager().getDefaultDisplay().getHeight());
                wl.gravity = Gravity.CENTER;
                // 以下这两句是为了保证按钮可以水平满屏
                wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
                wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                // 设置显示位置
                mDynamicSelectedDialog.onWindowAttributesChanged(wl);
                // 设置点击外围解散
                mDynamicSelectedDialog.setCanceledOnTouchOutside(true);
                mDynamicSelectedDialog.show();

            }

            @Override
            public void onHeartClick(View v, int position) {
                praiseSkill(position);
            }

            @Override
            public void onCommentClick(View v, int position) {

            }
        });

        mRecyclerView.setAdapter(mAdapter);

        //下面的 是添加的
   //     View header = LayoutInflater.from(getContext()).inflate(R.layout.header,mRecyclerView, false);
  //      mAdapter.setHeaderView(header);

   //     View footer = LayoutInflater.from(getContext()).inflate(R.layout.footer, mRecyclerView, false);
  //      mAdapter.setFooterView(footer);


        swipeToLoadLayout = (SwipeToLoadLayout) view.findViewById(R.id.swipeToLoadLayout);
        //为swipeToLoadLayout设置下拉刷新监听者
        swipeToLoadLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {

                queryData(STATE_REFRESH,15);
                if(mAdapter.getmList().size()<=6){
                    queryData(STATE_MORE,10);
                }

            }
        });
        //为swipeToLoadLayout设置上拉加载更多监听者
        swipeToLoadLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                queryData(STATE_MORE,10);
                if(mAdapter.getmList().size()<=6){
                    queryData(STATE_MORE,10);
                }
            }
        });
    }


    private void initHomeDate(){
        //从服务器上获取屏蔽的动态信息
        downLoadUserShieldings();
        //从度武器上获取点赞的信息
        downLoadUserPraises();
        //刷新15条数据
        queryData(STATE_REFRESH,15);
        if(mAdapter.getmList().size()<=5){
            queryData(STATE_MORE,10);
        }

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                addLiveLick(mClickCount,msg.obj.toString());
                delayTimer.cancel();
                super.handleMessage(msg);
            }
        };

    }

    private void queryData(final int actionType,int limit) {
        BmobQuery<AlumniCircle> query = new BmobQuery<>();
        // 按时间降序查询
        query.order("-createdAt");
        // 如果是加载更多
        if (actionType == STATE_MORE) {
            // 只查询小于等于最后一个item发表时间的数据
            if(oldestDynamicDate!=null) {
                query.addWhereLessThanOrEqualTo("createdAt", new BmobDate(oldestDynamicDate));
            }
        } else {
            // 下拉刷新
        }
        // 设置每页数据个数
        query.setLimit(limit);
        // 查找数据
        query.findObjects(new FindListener<AlumniCircle>() {
            @Override
            public void done(List<AlumniCircle>  Serverlist, BmobException e) {
                if(e==null){
                    if (Serverlist.size() > 0) {
                        List <String >sendphones=new ArrayList<>();
                        if (actionType == STATE_REFRESH) {
                            // 当是下拉刷新操作时,清空adaper，重新添加数据
                            mAdapter.clearDate();
                            //设置下拉刷新结束
                            swipeToLoadLayout.setRefreshing(false);
                        }else{
                            //设置上拉加载更多结束
                            swipeToLoadLayout.setLoadingMore(false);
                        }
                        // 将本次查询的数据添加到adapter中
                        for (AlumniCircle td : Serverlist) {
                            if(!isObjectIDShielded(td.getObjectId())) {
                                //不是屏蔽的信息则可以进行添加
                                if(isObjectIDPraiseed(td.getObjectId())) {
                                    //被点赞的
                                    td.setIsPraise(1);
                                }else {
                                    td.setIsPraise(0);
                                }
                                mAdapter.addDatetoFoot(td);
                                sendphones.add(td.getSenderPhone());

                            }
                        }

                        //下载发送者头像
                        downloadSenderHeadFile(sendphones);
                        // 更新最老的数据时间// 处理时间查询
                        String lastTime = Serverlist.get(Serverlist.size() - 1).getCreatedAt();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try {
                            oldestDynamicDate = sdf.parse(lastTime);
                        } catch (ParseException ee) {
                            ee.printStackTrace();
                        }
                        if (actionType == STATE_REFRESH) {
                            mAdapter.notifyDataSetChanged();
                        }


                    } else if (actionType == STATE_MORE) {
                        Toast.makeText(getActivity(),"没有更多技能了",Toast.LENGTH_SHORT).show();
                        swipeToLoadLayout.setLoadingMore(false);
                    } else if (actionType == STATE_REFRESH) {
                        Toast.makeText(getActivity(),"没有数据",Toast.LENGTH_SHORT).show();
                        swipeToLoadLayout.setRefreshing(false);
                    }

                }else{
                    //错误
                    if (actionType == STATE_MORE) {
                        swipeToLoadLayout.setLoadingMore(false);
                        Toast.makeText(getActivity(),"加载失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    }else {
                        swipeToLoadLayout.setRefreshing(false);
                        Toast.makeText(getActivity(),"刷新失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    }
                }
            }

        });
    }
    //删除技能墙中的一个技能
    private void deleteSkill(final int position){
        AlumniCircle ac=new AlumniCircle();
        ac.setObjectId(mAdapter.getmList().get(position).getObjectId());
        ac.delete(new UpdateListener(){
            @Override
            public void done(BmobException e) {
                if(e==null){
                    mAdapter.getmList().remove(position);
                    mAdapter.notifyItemRemoved(position);
                    mAdapter.notifyItemRangeChanged(position,mAdapter.getmList().size()-position);
                }else{
                    Toast.makeText(getActivity(),"删除失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
        //删除服务器中的图片
        String[] urls =new String[mAdapter.getmList().get(position).getPhotoNumber()];
        for(int i=0;i<urls.length;i++){
            urls[i]=mAdapter.getmList().get(position).getphotos().get(i).toString();
        }
        BmobFile.deleteBatch(urls, new DeleteBatchListener() {
            @Override
            public void done(String[] failUrls, BmobException e) {
                if(e==null){
                }else{
                    if(failUrls!=null){
                        //toast("删除失败个数："+failUrls.length+","+e.toString());
                    }else{
                        //toast("全部文件删除失败："+e.getErrorCode()+","+e.toString());
                    }
                }
            }
        });
    }

    //当前用户屏蔽某条动态
    private void shieldSkill(final int position){
        final MainActivity t = (MainActivity) getActivity();
        if(t==null) return;

        BmobQuery<shielding> query = new BmobQuery<shielding>();
        query.addWhereEqualTo("userID", t.getCurrentUser().getUsername());
        //执行查询方法
        query.findObjects(new FindListener<shielding>() {
            @Override
            public void done(final List<shielding> object, BmobException e) {
                if (e == null) {
                    final SharedPreferences.Editor editor=getContext().getSharedPreferences(t.getCurrentUser().getUsername()+"_shieldings", Context.MODE_PRIVATE).edit();
                    if(object.size()==1){
                        //服务器存在这条，则修改，增加屏蔽数据
                        final shielding sd=new shielding();
                        sd.setObjectIDs(object.get(0).getObjectIDs());
                        sd.addObjectID(mAdapter.getmList().get(position).getObjectId());
                        sd.update(object.get(0).getObjectId(),new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if(e==null){
                                    editor.putInt("size",1+object.get(0).getObjectIDs().size());
                                    editor.putString("num_"+(sd.getObjectIDs().size()-1),mAdapter.getmList().get(position).getObjectId());
                                    editor.apply();
                                    mAdapter.getmList().remove(position);
                                    mAdapter.notifyItemRemoved(position);
                                    mAdapter.notifyItemRangeChanged(position,mAdapter.getmList().size()-position);
                                }else {
                                    Toast.makeText(getActivity(),"操作失败",Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }else if(object.size()==0){
                        //服务器没有找个人的屏蔽数据，则应该增加
                        final shielding sd=new shielding();
                        sd.setUserID(t.getCurrentUser().getUsername());
                        sd.addObjectID(mAdapter.getmList().get(position).getObjectId());
                        sd.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if(e==null){
                                    editor.putInt("size",1);
                                    editor.putString("num_0",mAdapter.getmList().get(position).getObjectId());
                                    editor.apply();
                                    mAdapter.getmList().remove(position);
                                    mAdapter.notifyItemRemoved(position);
                                    mAdapter.notifyItemRangeChanged(position,mAdapter.getmList().size()-position);
                                }else {
                                    Toast.makeText(getActivity(),"操作失败",Toast.LENGTH_SHORT);
                                }
                            }
                        });
                    }
                }else {

                }
            }
        });
    }

    long mLastTime = 0;
    long mCurTime = 0;
    private int mClickCount = 0;
    private Timer delayTimer;
    private TimerTask timeTask;
    int DELAY = 500;
    private static Handler  mHandler;
    //当前用户点赞某条动态
    private void praiseSkill(final int position){
        final MainActivity t = (MainActivity) getActivity();
        if(t==null) return;

        final SharedPreferences.Editor editor=getContext().getSharedPreferences(t.getCurrentUser().getUsername()+"_praises", Context.MODE_PRIVATE).edit();

        SharedPreferences preferences=getContext().getSharedPreferences(t.getCurrentUser().getUsername()+"_praises",Context.MODE_PRIVATE);

        if(preferences.getInt(mAdapter.getmList().get(position).getObjectId(),0)==0){
            //未点赞状态变成点赞状态
            editor.putInt(mAdapter.getmList().get(position).getObjectId(),1);
            editor.apply();
            mAdapter.getmList().get(position).setIsPraise(1);
            mAdapter.notifyItemChanged(position,1);

            //调整服务器上的数据
            BmobQuery<praises> query = new BmobQuery<praises>();
            query.addWhereEqualTo("userID", t.getCurrentUser().getUsername());
            //执行查询方法
            query.findObjects(new FindListener<praises>() {
                @Override
                public void done(final List<praises> object, BmobException e) {
                    if (e == null) {
                        if(object.size()==1){
                            //服务器存在这条，则修改，增加点赞数据
                            final praises sd=new praises();
                            sd.setObjectIDs(object.get(0).getObjectIDs());
                            sd.addObjectID(mAdapter.getmList().get(position).getObjectId());
                            sd.update(object.get(0).getObjectId(),new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    if(e==null){
                                    }else {
                                    }
                                }
                            });
                        }else if(object.size()==0){
                            //服务器没有找个人的点赞数据，则应该增加
                            final praises sd=new praises();
                            sd.setUserID(t.getCurrentUser().getUsername());
                            sd.addObjectID(mAdapter.getmList().get(position).getObjectId());
                            sd.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if(e==null){
                                    }else {
                                    }
                                }
                            });
                        }
                    }else {

                    }
                }
            });

        }
        int count=mAdapter.getmList().get(position).getPraiseNumber();
        count++;
        mAdapter.getmList().get(position).setPraiseNumber(count);
        mAdapter.notifyItemChanged(position,1);

        mCurTime = System.currentTimeMillis();

        if (mCurTime - mLastTime < DELAY) {
            mClickCount++;
        } else {
            mClickCount = 1;
        }
        delay(mAdapter.getmList().get(position).getObjectId());
        mLastTime = mCurTime;
    }
    private void delay(final String objid) {
        if (timeTask != null)
            timeTask.cancel();

        timeTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.obj=objid;
                mHandler.sendMessage(message);
            }
        };
        delayTimer = new Timer();
        delayTimer.schedule(timeTask, DELAY);
    }
    private void addLiveLick(final int count, final String objid){
        BmobQuery<AlumniCircle> query = new BmobQuery<AlumniCircle>();
        query.getObject(objid, new QueryListener<AlumniCircle>() {
            @Override
            public void done(AlumniCircle alumniCircle, BmobException e) {
                if(e==null){
                    int num=alumniCircle.getPraiseNumber();
                    AlumniCircle ac=new AlumniCircle();
                    ac.setPraiseNumber(num+count);
                    ac.update(objid, new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                        }
                    });
                }
            }
        });
    }

    //打开应用时从服务器上获取此用户点赞的信息
    private void downLoadUserPraises(){
        final MainActivity t = (MainActivity) getActivity();
        if(t==null) return;

        BmobQuery<praises> query = new BmobQuery<praises>();
        query.addWhereEqualTo("userID", t.getCurrentUser().getUsername());
        //执行查询方法
        query.findObjects(new FindListener<praises>() {
            @Override
            public void done(final List<praises> object, BmobException e) {
                if (e == null) {
                    final SharedPreferences.Editor editor=getContext().getSharedPreferences(t.getCurrentUser().getUsername()+"_praises", Context.MODE_PRIVATE).edit();
                    if(object.size()==1){
                        //服务器存在用户的信息，下载到本地
                        for(int i=0;i<object.get(0).getObjectIDs().size();i++) {
                            editor.putInt(object.get(0).getObjectIDs().get(i).toString(),1);
                        }
                        editor.apply();
                    }
                }
            }
        });
    }
    //打开应用时从服务器上获取此用户的信息
    private void downLoadUserShieldings(){
        final MainActivity t = (MainActivity) getActivity();
        if(t==null) return;
        BmobQuery<shielding> query = new BmobQuery<shielding>();
        query.addWhereEqualTo("userID", t.getCurrentUser().getUsername());
        //执行查询方法
        query.findObjects(new FindListener<shielding>() {
            @Override
            public void done(final List<shielding> object, BmobException e) {
                if (e == null) {
                    final SharedPreferences.Editor editor=getContext().getSharedPreferences(t.getCurrentUser().getUsername()+"_shieldings", Context.MODE_PRIVATE).edit();
                    if(object.size()==1){
                        //服务器存在用户的信息，下载到本地
                        editor.putInt("size",object.get(0).getObjectIDs().size());
                        for(int i=0;i<object.get(0).getObjectIDs().size();i++) {
                            editor.putString("num_" + i,object.get(0).getObjectIDs().get(i).toString());
                        }
                        editor.apply();
                    }else if(object.size()==0){
                        //服务器没有找个人的屏蔽数据
                    }
                }else {

                }
            }
        });
    }

    //判断这个是否是屏蔽的动态
    private boolean isObjectIDShielded(String s){
        final MainActivity t = (MainActivity) getActivity();
        if(t==null) return false;
        SharedPreferences preferences=getContext().getSharedPreferences(t.getCurrentUser().getUsername()+"_shieldings",Context.MODE_PRIVATE);
        for(int i=0;i<preferences.getInt("size",0);i++){
            if(s.equals(preferences.getString("num_"+i,""))){
                return true;
            }
        }
        return  false;
    }
    //判断是否被点赞
    private boolean isObjectIDPraiseed(String s){
        final MainActivity t = (MainActivity) getActivity();
        if(t==null) return false;
        SharedPreferences preferences=getContext().getSharedPreferences(t.getCurrentUser().getUsername()+"_praises",Context.MODE_PRIVATE);
        if(preferences.getInt(s,0)==1){
            return true;
        }
        return  false;
    }


    private void downloadSenderHeadFile(final List<String> sendphones ) {
        BmobQuery<UserInfo> bmobQuery;

        final SharedPreferences.Editor editor=getContext().getSharedPreferences("heads_cache", Context.MODE_PRIVATE).edit();

        final SharedPreferences preferences=getContext().getSharedPreferences("heads_cache",Context.MODE_PRIVATE);


        for(int i=0;i<sendphones.size();i++) {

            bmobQuery = new BmobQuery<UserInfo>();
            bmobQuery.addWhereEqualTo("mobilePhoneNumber", sendphones.get(i));
            bmobQuery.findObjects(new FindListener<UserInfo>() {
                @Override
                public void done(List<UserInfo> list, BmobException e) {
                    if (e == null) {
                        if (list.size() == 1) {
                            String phone=list.get(0).getMobilePhoneNumber();
                            String serviceUrl=list.get(0).getHeadFileUrl();

                            String localUrl=preferences.getString(phone," ");
                            BmobFile file=new BmobFile("head"+phone+".jpg","",serviceUrl);
                            //允许设置下载文件的存储路径，默认下载文件的目录为：context.getApplicationContext().getCacheDir()+"/bmob/"
                            File saveFile = new File(getContext().getExternalCacheDir()+"/heads/", file.getFilename());
                            //如果服务器与本地的头像url不一样或者本地不存在头像，说明更换了头像或者还没有头像
                            if(!localUrl.equals(serviceUrl)||!saveFile.exists()){

                                editor.putString(phone,serviceUrl);
                                editor.apply();



                                if (!saveFile.getParentFile().exists()) {
                                    saveFile.getParentFile().mkdirs();
                                }

                                file.download(saveFile, new DownloadFileListener() {
                                    @Override public void onStart(){}
                                    @Override public void onProgress(Integer value, long newworkSpeed) {}
                                    @Override
                                    public void done(String savePath,BmobException e) {
                                        if(e==null){
                                            //下载完刷新
                                            mAdapter.notifyDataSetChanged();
                                        }
                                    }
                                });
                            }

                        }
                    }
                }
            });
        }
    }
    /**
     * Init the fragment
     */

    private ImageView imageView_cover;
    private ImageView imageView_head;

    private void initPersonalMenu(View view) {

        final MainActivity t = (MainActivity) getActivity();
        imageView_cover=(ImageView)view.findViewById(R.id.iv_cover);
        imageView_head=(ImageView)view.findViewById(R.id.iv_head);
        //获取本地封面\
        String coverPath;
        coverPath=getContext().getExternalCacheDir()+"/CoverImage"+t.getCurrentUser().getMobilePhoneNumber()+".jpg";
        File coverfile=new File(coverPath);
        if(!coverfile.exists()){
            //如果本地不存在文件 则进行下载
          //  Toast.makeText(getActivity(), "本地没有封面，开始下载", Toast.LENGTH_SHORT).show();
            t.downloadCoverFile(new MainActivity.downloadCoverListener() {
                @Override
                public void downloadCoverDone(String path) {
                    Bitmap bitmap= BitmapFactory.decodeFile(path);
                    imageView_cover.setImageBitmap(bitmap);
                }
            });
        }else {
            //本地存在封面文件，直接使用
            Bitmap bitmap = BitmapFactory.decodeFile(coverPath);
            imageView_cover.setImageBitmap(bitmap);
        }
        //获取本地头像
        String headPath=getContext().getExternalCacheDir()+"/HeadImage"+t.getCurrentUser().getMobilePhoneNumber()+".jpg";
        File headfile=new File(headPath);
        if(!headfile.exists()){
            //如果本地不存在头像 则进行下载
            t.downloadHeadFile(new MainActivity.downloadHeadListener() {
                @Override
                public void downloadHeadDone(String path) {
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    imageView_head.setImageBitmap(bitmap);
                }
            });
        }else {
            //本地存在封面文件，直接使用
            Bitmap bitmap = BitmapFactory.decodeFile(headPath);
            imageView_head.setImageBitmap(bitmap);
        }

        imageView_cover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择新封面
                t.chooseImage(1,imageView_cover.getMeasuredWidth(),imageView_cover.getMeasuredHeight());
            }
        });;
        imageView_head.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //选择新头像
                t.chooseImage(2,0,0);
            }
        });


    }


    public ImageView getImageView_cover(){return imageView_cover;}
    public ImageView getImageView_head(){return imageView_head;}
    /**
     * Refresh
     */
    public void refresh() {

    }

    /**
     * Called when a fragment will be displayed
     */
    public void willBeDisplayed() {
        // Do what you want here, for example animate the content
        if (fragmentContainer != null) {
            Animation fadeIn = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_in);
            fragmentContainer.startAnimation(fadeIn);
        }
    }

    /**
     * Called when a fragment will be hidden
     */
    public void willBeHidden() {
        if (fragmentContainer != null) {
            Animation fadeOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out);
            fragmentContainer.startAnimation(fadeOut);
        }
    }


}
